package bill.study.collection;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

public class MyCollectionOfCollections <E> implements Iterable<E> {
	private Collection<Collection<E>> data;
	MyCollectionOfCollections(Collection<Collection<E>> d){
		this.data = d;
	}
	public Iterator<E> iterator(){
		return new MyIterator();
	}
	
	private class MyIterator implements Iterator<E>{
		private Iterator<Collection<E>> parent; // why does not this work?
		private Iterator<E> child;
		MyIterator(){
			this.parent = data.iterator();
			while(this.parent.hasNext()){
				Collection<E> con = (Collection<E>)parent.next();
				if(!con.isEmpty()){
					child = con.iterator();
					break;
				}
			}
		}
		public boolean hasNext(){
			if(this.child.hasNext()){
				return true;
			}else{
				while(this.parent.hasNext()){
					Collection<E> con = (Collection<E>)parent.next();
					if(!con.isEmpty()){
						child = con.iterator();
						return true;
					}
				}
				return false;
			}
		}
		
		public E next(){
			return child.next();
		}
		
		public void remove(){
			child.remove();
		}
	}
	
	
	public static void main(String [] a){
		Collection<Collection<Object>> d = new ArrayList<Collection<Object>>();
		d.add(Collections.emptyList());
		Set<Object> s = new HashSet<Object>();
		s.add("Bill");
		s.add("Shu");
		d.add(s);
		d.add(Collections.emptySet());
		List<Object> l = new LinkedList<Object>();
		l.add("Simon");
		l.add("Tony");
		d.add(l);
		
		MyCollectionOfCollections m = new MyCollectionOfCollections(d);
		
		for(Object o: m){
			System.out.println(o);
		}
	}
}
